'''
都会天使医疗保险
'''

import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests,time
from common.helper import Helper

class Spider( object ):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "都会天使医疗保险"

    # 生成产品信息
    def genProductInfo(self):

        # 年龄区间
        years = [ str( i ) for i in range( 0,101)]
        # 有无社保 844无社保 843 有社保
        socialSec = ["P000000844","P000000843"]

        for v in product( years,socialSec ):

            birth = str(2019 - int(v[0])) + '-10-01'

            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(v[0],birth,v[1]))

            self.mysql._conn.commit()

            print("%s写入数据库成功"%self.name)

    #执行爬虫
    def requestJson(self,dt=None):

        appid = dt["birth"].replace("-","")

        data = {

                "appName":"",
                "appSex": "M",
                "appidType": "A",
                "appidNo": "211321"+appid+"5619",
                "appBirthday": dt["birth"],
                "appPhone":"",
                "appPro": "110000",
                "appCity": "110100",
                "appAddress":"",
                "appEmail":"",
                "name":"",
                "sex": "M",
                "idType": "A",
                "idNo": "211321"+appid+"5619",
                "birthday": dt["birth"],
                "phone":"",
                "pro":"110000",
                "city": "110100",
                "address":"",
                "email":"",
                "source": "CUS000000046",
                "planCode": dt["socialSec"],
                "planAmnt": "1000000",
                "polTerm": "1",
                "poltermType": "Y",
                "payPeriod": "1",
                "payIntv": "12",
                "relation": "0",
                "validate":""
            }


        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=urlencode(data))

        if r.status_code == 200 and r.json()["success"]:

            price = Helper.decimalParse( r.json()["msg"])

            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price,
            }

            # 执行数据库更新操作
            self.mysql.updatePrice(data)

            print("产品价格更新成功:", data["price"])

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            self.mysql.updateTask(data)

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }

            self.mysql.updateTask(data)

            self.requestJson(dt)


if __name__ == '__main__':

    s = Spider()
    s.main()

